﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Interface;
using Domain;
using EntityFrameworkContrib.PostSharp4EF;

namespace Server
{
    public class SchoolService : ISchoolService
    {
        public Person GetPerson(int id, bool fetchEnrollments, bool fetchCourses)
        {
            using (SchoolContext context = new SchoolContext())
            {
                Person p = (from person in context.Person
                            where person.PersonID  == id
                               select person).First();

                if (fetchEnrollments)
                {
                    ((IRelationshipLoader)p).Load("Enrollments");
                    foreach (Enrollment r in p.Enrollments)
                    {
                        ((IRelationshipLoader)r).Load("Course");
                        ((IRelationshipLoader)r).Load("Person");
                    }
                }
                
                if (fetchCourses)
                {
                    ((IRelationshipLoader)p).Load("Courses");
                    foreach (Course c in p.Courses)
                    {
                        ((IRelationshipLoader)c).Load("Department");
                        ((IRelationshipLoader)c).Load("Enrollments");
                        ((IRelationshipLoader)c).Load("Persons");

                    }
                }

                ((IContextAware)p).CreateSerializableState(context);

                return p;
            }

        }


        public void SavePerson(Person person)
        {
            using (SchoolContext context = new SchoolContext())
            {
                ((IContextAware)person).AttachGraphToContext(context, entity => entity.GetType().Name);

                context.SaveChanges();
            }
        }


        public IList<Course> GetCourses()
        {
            using (SchoolContext context = new SchoolContext())
            {
                List<Course> courses = context.Course.ToList();
                courses.ForEach(crs => ((IContextAware)crs).CreateSerializableState(context));
                return courses;

            }
        }

        public IList<Department> GetDepartments()
        {
            using (SchoolContext context = new SchoolContext())
            {
                List<Department> deps = context.Department.ToList();
                deps.ForEach(dp => ((IContextAware)dp).CreateSerializableState(context));
                return deps;
            }
        }

    }
}
